<?php

namespace App\Http\Middleware\Merchant;

use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use Closure;
use Tymon\JWTAuth\Http\Middleware\Authenticate;

class PublicDeviceSignAuth extends Authenticate
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $serialNo = $request->get('serialNo');
        if (empty($serialNo)) {
            throw new CommonException(CommonCodeEnum::ERR_PARAM_ERROR);
        }

        $timestamp = $request->get('timestamp');
        if (empty($timestamp)) {
            throw new CommonException(CommonCodeEnum::ERR_PARAM_ERROR);
        }

        $sign = $request->get('sign');
        if (empty($sign)) {
            throw new CommonException(CommonCodeEnum::ERR_PARAM_ERROR);
        }

        $genSign = strtolower(md5(strtolower($serialNo) . $timestamp . 20210717));
        if ($genSign != $sign) {
            throw new CommonException(CommonCodeEnum::ERR_SIGN_ERROR);
        }

        return $next($request);
    }
}
